package com.zc.manager.device.domain;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.ruoyi.common.annotation.Excel;
import com.zc.core.metadata.Converter;
import com.zc.core.metadata.DataType;
import com.zc.core.metadata.PropertyMetadata;
import lombok.Data;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import java.util.Date;

/**
 * 设备标签
 * @author xiepufeng
 */
@Data
public class IotDeviceTags  {

    private static final long serialVersionUID = 1L;

    /** 主键 */
    private Long id;

    /** 标签名称 */
    @Excel(name = "标签名称")
    @NotBlank(message = "标签名称不能为空")
    @Size(max = 30, message = "标签名称长度不能超过30个字符")
    private String name;

    /** 设备id */
    private String deviceId;

    /** 数据类型 */
    @Excel(name = "数据类型")
    @Pattern(regexp = "int|double|string", message = "无效的数据类型")
    private String type;

    /** 标签值 */
    @Excel(name = "标签值")
    @NotBlank(message = "标签值不能为空")
    @Size(max = 50, message = "标签值长度不能超过50个字符")
    private String value;

    /** 标签key */
    @Excel(name = "标签key")
    @NotBlank(message = "标签key不能为空")
    @Size(max = 50, message = "标签key长度不能超过50个字符")
    private String key;

    /** 描述 */
    @Excel(name = "描述")
    @Size(max = 200, message = "描述不能超过200个字符")
    private String description;

    //创建时间
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone="GMT+8")
    @Excel(name = "创建时间")
    private Date createTime;

    //更新时间
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone="GMT+8")
    @Excel(name = "更新时间")
    private Date updateTime;

    public static IotDeviceTags of(PropertyMetadata property) {
        IotDeviceTags entity = new IotDeviceTags();
        entity.setKey(property.getId());
        entity.setName(property.getName());
        entity.setType(property.getValueType().getId());
        entity.setDescription(property.getDescription());
        entity.setCreateTime(new Date());
        return entity;
    }

    public static IotDeviceTags of(PropertyMetadata property, Object value) {
        IotDeviceTags tag = of(property);

        DataType type = property.getValueType();
        if (type instanceof Converter) {
            Object newValue = ((Converter<?>) type).convert(value);
            if (newValue != null) {
                value = newValue;
            }
        }
        tag.setValue(String.valueOf(value));
        return tag;
    }
}
